package main.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress;

public class CellRangeAddressUtil {
	List<Map<String,Object>> rows;
	//菜单模块名称
	Map<String,Integer> firstCol;
	//一级菜单名称
	//Map<String,Integer> secondCol;
	//二级菜单名称-有链接，如果有合并单元格，说明菜单下面有按钮
	//Map<String,Integer> thirdCol;

	
	Sheet sheet;

	public CellRangeAddressUtil(Sheet sheet) {
		super();
		this.sheet = sheet;
		firstCol=new HashMap<String, Integer>();
		sortCellRange();
	}
	//对sheet表格排序,获取合并至最后的部分
	private void sortCellRange(){
		int sheetMergeCount = sheet.getNumMergedRegions();
		for(int i = 0 ; i < sheetMergeCount ; i++ ){
			CellRangeAddress ca = sheet.getMergedRegion(i);
			int firstColumn = ca.getFirstColumn();
			int firstRow = ca.getFirstRow();
			int lastRow = ca.getLastRow();
			if(lastRow>firstRow)
				firstCol.put(firstColumn+":"+firstRow, lastRow);
		}
	}
	
	//获取单元格合并的行数，如果不是合并单元格，则返回null；
	public Integer getMergeRow(Cell cell){
		if(cell.getColumnIndex()>2){
			return null;
		}
		
		CellAddress ca=cell.getAddress();
		Integer range=firstCol.get(ca.getColumn()+":"+ca.getRow());
		
		if(range==null){//再判断上下是否一致，一致的话认为是合并单元格
			range=getRepeatRow(cell, cell.getStringCellValue());
		}
		
		if(range>cell.getRowIndex()){
			return range;
		}
		
		return null;
		/*if(range>0){
		}
		return -1;*/
	}
	
	//递归查询，如果上面的值和下面的值一样，则也认为是合并单元格
	public Integer getRepeatRow(Cell cell,String topValue){
		String value=cell.getStringCellValue();
		
		if(!topValue.equals(value)){
			return cell.getRowIndex()-1;
		}
		
		int row=cell.getRowIndex()+1;
		int col=cell.getColumnIndex();
		Cell nextCell=cell.getSheet().getRow(row).getCell(col);
		return getRepeatRow(nextCell,value);
	}
	
	public Map<String, Integer> getFirstCol() {
		return firstCol;
	}
	
}
